"""
使用示例
演示如何使用各个模块
"""
import sys
from pathlib import Path

# 添加项目根目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from data_collection import PubMedCrawler, DataStorage
from retrieval import TextEmbedder, FAISSIndexer
from summarization import RAGSummarizer
from evaluation import MetricsEvaluator


def example_crawl_and_store():
    """示例：爬取并存储论文"""
    print("=== 示例1：爬取并存储论文 ===")
    
    # 1. 爬取论文
    crawler = PubMedCrawler()
    papers = crawler.crawl_recent_papers(
        query="COVID-19 vaccine", 
        max_results=5
    )
    
    # 2. 保存到数据库
    storage = DataStorage()
    storage.save_papers(papers)
    
    print(f"成功爬取并保存 {len(papers)} 篇论文")
    print(f"数据库位置: {storage.db_path}")


def example_search():
    """示例：搜索文献"""
    print("\n=== 示例2：搜索文献 ===")
    
    # 1. 加载索引
    indexer = FAISSIndexer()
    indexer.load("models/faiss_indices/medical_index")
    
    # 2. 向量化查询
    embedder = TextEmbedder()
    query = "How effective are COVID-19 vaccines?"
    query_vector = embedder.encode_texts([query])
    
    # 3. 检索
    results = indexer.search_by_vector(query_vector, top_k=5)
    
    # 4. 获取详情
    storage = DataStorage()
    for result in results:
        paper = storage.get_paper_by_pmid(result["pmid"])
        print(f"\n标题: {paper['title']}")
        print(f"相关性: {result['score']:.3f}")


def example_summarize():
    """示例：生成摘要"""
    print("\n=== 示例3：生成摘要 ===")
    
    # 1. 获取论文
    storage = DataStorage()
    papers = storage.get_all_papers(limit=3)
    
    # 2. 生成摘要
    summarizer = RAGSummarizer()
    summary = summarizer.generate_summary(
        papers, 
        query="COVID-19 treatment"
    )
    
    print("生成的摘要:")
    print(summary)


def example_evaluate():
    """示例：评估性能"""
    print("\n=== 示例4：评估检索性能 ===")
    
    evaluator = MetricsEvaluator()
    
    # 模拟相关论文和检索结果
    relevant_pmids = ["PMID1", "PMID2", "PMID3", "PMID4", "PMID5"]
    retrieved_pmids = ["PMID1", "PMID6", "PMID2", "PMID7", "PMID3", 
                       "PMID8", "PMID9", "PMID10", "PMID4", "PMID11"]
    
    results = evaluator.evaluate_retrieval(relevant_pmids, retrieved_pmids, k=10)
    
    print(f"Precision@10: {results['precision@k']:.2%}")
    print(f"Recall@10: {results['recall@k']:.2%}")
    print(f"F1@10: {results['f1@k']:.2%}")


def example_end_to_end():
    """示例：端到端流程"""
    print("\n=== 示例5：端到端流程 ===")
    
    # 1. 爬取数据
    print("1. 爬取数据...")
    crawler = PubMedCrawler()
    papers = crawler.crawl_recent_papers(query="diabetes", max_results=10)
    
    storage = DataStorage()
    storage.save_papers(papers)
    
    # 2. 构建索引
    print("2. 构建索引...")
    embedder = TextEmbedder()
    embeddings = embedder.encode_papers(papers)
    
    indexer = FAISSIndexer(dimension=embeddings.shape[1])
    pmids = [p["pmid"] for p in papers]
    indexer.add_vectors(embeddings, pmids)
    
    # 3. 搜索
    print("3. 搜索文献...")
    query = "diabetes medication"
    query_vector = embedder.encode_texts([query])
    results = indexer.search_by_vector(query_vector, top_k=5)
    
    # 4. 获取论文详情
    retrieved_papers = []
    for r in results:
        paper = storage.get_paper_by_pmid(r["pmid"])
        paper["relevance_score"] = r["score"]
        retrieved_papers.append(paper)
    
    # 5. 生成摘要
    print("4. 生成摘要...")
    summarizer = RAGSummarizer()
    summary = summarizer.generate_summary(retrieved_papers, query=query)
    
    print("\n查询:", query)
    print("\n摘要:", summary)
    print("\n检索到的论文:")
    for paper in retrieved_papers:
        print(f"- {paper['title']} ({paper['relevance_score']:.3f})")


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="运行示例代码")
    parser.add_argument("--example", type=int, choices=[1, 2, 3, 4, 5],
                       help="要运行的示例编号 (1-5)")
    
    args = parser.parse_args()
    
    examples = {
        1: example_crawl_and_store,
        2: example_search,
        3: example_summarize,
        4: example_evaluate,
        5: example_end_to_end
    }
    
    if args.example:
        examples[args.example]()
    else:
        print("未指定示例，运行所有示例...")
        example_crawl_and_store()
        example_search()
        example_summarize()
        example_evaluate()
